let app = require('express')();
let server = require('http').Server(app);
let io = require('socket.io')(server);

const mysql = require('mysql');
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'test'
});
//  开启连接
connection.connect();

if (connection) {
    console.log('连接成功!')
}else {
    console.log('连接失败!')
}
var sql = 'SELECT * FROM student ';

function getSql() {
    var results = []   // 存放查询的数据
    function fun() {
        return new Promise(function (resolve) {
            connection.query(sql, data, function (err, result) {
                if (err) {
                    console.log('[SELECT ERROR] - ', err.message);
                    return;
                }
                for (let i = 0; i < result.length; i++) {
                    results.push({"Time": result[i].Time, "Temp": result[i].Temp, "Hum": result[i].Hum, "Smoke": result[i].Smoke});
                }
                resolve(results)
            })
        });
    }

    async function compute() {
        var x = await fun();
        return x;
    }

    var a = compute()
    return a;
}

var data = [];  // 存放处理后的数据
getSql().then(function (msg) {
    data = msg;
    console.log(data)
})

// 监听端口
server.listen(8080);

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.js');
});

io.on('connection', function (socket) {
    socket.emit('news', {datas: data});
    console.log('客户端请求返回数据!')
});

/*
*   定时查询数据库数据，如果有变化重新发送给客户端
* */
var new_data = [];  // 存放更新的数据
setInterval(function () {
    connection.query(sql, function (err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            for (let i = 0; i < result.length; i++) {
                new_data.push({"Time": result[i].Time, "Temp": result[i].Temp, "Hum": result[i].Hum, "Smoke": result[i].Smoke});
            }
            if (data != new_data) {
                data = new_data;
                io.emit('news', {datas: data});
            }
        }
        // 发送完后清空数组
        new_data = [];
    })
}, 3000);



